package org.vacoor.xqq.ui.comp.combo;

import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.awt.*;

/**
 * @author Vacoor
 */
public class IconifyComboBox extends JComboBox {
    private static final long serialVersionUID = 1L;
    private EventListenerList listeners = new EventListenerList();

    public IconifyComboBox(IconifyComboItem[] items) {
        this(new DefaultComboBoxModel(items));
    }

    public IconifyComboBox(ComboBoxModel model) {
        super(model);
        init();
    }

    private void init() {
        this.setUI(new IconifyItemComboBoxUI()); //设置UI
        this.setEditable(true);
        this.setPreferredSize(new Dimension(180, 26));  //设置缺省大小
        this.setBackground(Color.WHITE);
    }

    @Override
    public void addItem(Object anObject) {
        System.out.println("---------------");
    }

    @Override
    public void configureEditor(ComboBoxEditor anEditor, Object anItem) {
        super.configureEditor(anEditor, anItem);
    }

    //添加自己的监听器
    public void addIconifyItemListener(IconifyItemListener listener) {
        listeners.add(IconifyItemListener.class, listener);
    }

    public void removeIconifyItemListener(IconifyItemListener listener) {
        listeners.remove(IconifyItemListener.class, listener);
    }

    //以下三个方法用于实现接口中的方法
    protected void fireItemDeleting(IconifyComboItem item) {
        for (IconifyItemListener listener : listeners.getListeners(IconifyItemListener.class)) {
            listener.itemDeleting(item);
        }
    }

    protected void fireItemSelected(IconifyComboItem item) {
        //利用简化的for语句遍历
        for (IconifyItemListener listener : listeners.getListeners(IconifyItemListener.class)) {
            listener.itemSelected(item);
        }
    }

    protected void fireItemDeleted(IconifyComboItem item) {
        for (IconifyItemListener lt : listeners.getListeners(IconifyItemListener.class)) {
            lt.itemDeleted(item);
        }
    }
}